﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using umbraco.cms.businesslogic;
using umbraco.interfaces;

namespace umbraco.editorControls.ultimatepicker
{
    [ValidationProperty("IsValid")]
    public class ultimatePickerDataEditor : UpdatePanel, IDataEditor
    {
        private IData _data;
        string _configuration;

        private string[] config;
        private string controlType;

        private string[] dataValues;

        private TextBox childtxt;
        private DropDownList dropdownlistNodes;
        private CheckBoxList checkboxlistNodes;
        private RadioButtonList radiobuttonlistNodes;
        private ListBox listboxNodes;

        public ultimatePickerDataEditor(umbraco.interfaces.IData Data, string Configuration)
        {
            _data = Data;
            _configuration = Configuration;

            config = _configuration.Split("|".ToCharArray());
            controlType = config[0];

            RenderMode = UpdatePanelRenderMode.Inline;
        }

        public virtual bool TreatAsRichTextEditor
        {
            get { return false; }
        }

        public bool ShowLabel
        {
            get { return true; }
        }

        /// <summary>
        /// Internal logic for validation controls to detect whether or not it's valid (has to be public though) 
        /// </summary>
        /// <value>Am I valid?</value>
        public string IsValid
        {
            get
            {
                switch (controlType)
                {
                    case "auto-suggest":
                        if (childtxt.Text.Contains("|"))
                        {
                            return childtxt.Text;
                        }

                        break;
                    case "checkbox":
                        foreach (ListItem item in checkboxlistNodes.Items)
                        {
                            if (item.Selected)
                            {
                                return "valid";
                            }
                        }
                        break;
                    case "dropdown":
                        return dropdownlistNodes.SelectedValue;
                        break;
                    case "listbox":
                        foreach (ListItem item in listboxNodes.Items)
                        {
                            if (item.Selected)
                            {
                                return "valid";
                            }
                        }
                        break;
                    case "radiobox":
                        foreach (ListItem item in radiobuttonlistNodes.Items)
                        {
                            if (item.Selected)
                            {
                                return "valid";
                            }
                        }

                        break;

                }
                return "";
            }
        }

        public Control Editor { get { return this; } }

        public void Save()
        {
            string dataToSave = string.Empty;

            switch (controlType)
            {
                case "auto-suggest":
                    if (childtxt.Text.Contains("|"))
                    {
                        dataToSave = childtxt.Text.Split("|".ToCharArray())[1];
                    }
                    
                    break;
                case "checkbox":

                    foreach (ListItem item in checkboxlistNodes.Items)
                    {
                        if (item.Selected)
                        {
                            dataToSave += item.Value + ",";
                        }
                    }

                    if (dataToSave.Length > 0)
                    {
                        dataToSave = dataToSave.Substring(0, dataToSave.Length - 1);
                    }


                    break;
                case "dropdown":
                    dataToSave = dropdownlistNodes.SelectedValue;
                    break;
                case "listbox":
                    dataToSave = string.Empty;
                    foreach (ListItem item in listboxNodes.Items)
                    {
                        if (item.Selected)
                        {
                            dataToSave += item.Value + ",";
                        }
                    }

                    if (dataToSave.Length > 0)
                    {
                        dataToSave = dataToSave.Substring(0, dataToSave.Length - 1);
                    }
                    break;
                case "radiobox":
                    dataToSave = string.Empty;
                    foreach (ListItem item in radiobuttonlistNodes.Items)
                    {
                        if (item.Selected)
                        {
                            dataToSave += item.Value + ",";
                        }
                    }

                    if (dataToSave.Length > 0)
                    {
                        dataToSave = dataToSave.Substring(0, dataToSave.Length - 1);
                    }

                    break;

            }
            if (controlType != "auto-suggest")
            {
                this._data.Value = dataToSave;

            }
            else
            {
                if (dataToSave.Length > 0)
                {
                    this._data.Value = dataToSave;
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try
            {
                int parentNodeId = Convert.ToInt32(config[1]);
                CMSNode parentNode = new CMSNode(parentNodeId);

                string[] datavalues = _data.Value.ToString().Split(",".ToCharArray());

                switch (controlType)
                {
                    case "auto-suggest":
                        string script = "<style>/*AutoComplete flyout */\r\n                            .autocomplete_completionListElement \r\n                            {  \r\n\t                            visibility : hidden;\r\n\t                            margin : 0px !Important;\r\n\t                            padding: 0px !Important;\r\n                                background-color : #fff;\r\n\t                            color : #000;\r\n\t                            border : #ccc;\r\n\t                            border-width : 1px;\r\n\t                            border-style : solid;\r\n\t                            cursor : 'default';\r\n\t                            overflow : auto;\r\n\t                            height : 100px;\r\n                                text-align : left; \r\n                                list-style: none !Important;\r\n                                width: 400px !Important;\r\n                                z-index: 9999999;\r\n                            }\r\n                            .autocomplete_completionListElement li{\r\n                                display: block;\r\n                                padding: 1px !Important;\r\n                                margin: 0px;\r\n                            }\r\n                            /* AutoComplete highlighted item */\r\n\r\n                            .autocomplete_highlightedListItem\r\n                            {\r\n\t                            background-color: #ffff99;\r\n\t                            color: black;\r\n\t                            padding: 1px;\r\n                            }\r\n\r\n                            /* AutoComplete item */\r\n\r\n                            .autocomplete_listItem \r\n                            {\r\n\t                            background-color : window;\r\n\t                            color : windowtext;\r\n\t                            padding : 1px;\r\n                            }</style>";
                        this.Page.ClientScript.RegisterClientScriptBlock(script.GetType(), "ultimatePickerCss", script);
                        childtxt = new TextBox();
                        childtxt.ID = "ultimatePickerBox" + base.ID;
                        childtxt.AutoCompleteType = AutoCompleteType.Disabled;
                        childtxt.CssClass = "umbEditorTextField";
                        AutoCompleteExtender extender = new AutoCompleteExtender();
                        extender.TargetControlID = "ultimatePickerBox" + base.ID; ;
                        extender.ServiceMethod = "getNodes";
                        extender.ServicePath = "/umbraco/webservices/ultimatePickerAutoSuggest.asmx";
                        extender.MinimumPrefixLength = 2;
                        extender.CompletionInterval = 1000;
                        extender.EnableCaching = true;
                        extender.CompletionSetCount = 5;
                        extender.CompletionListCssClass = "autocomplete_completionListElement";
                        extender.CompletionListItemCssClass = "autocomplete_listItem";
                        extender.CompletionListHighlightedItemCssClass = "autocomplete_highlightedListItem";
                        extender.DelimiterCharacters = ";, :";
                        extender.UseContextKey = true;
                        extender.ContextKey = parentNodeId.ToString() + "|" + config[2];

                        if (_data.Value.ToString().Length > 3)
                        {
                            try
                            {
                                CMSNode firstSaved = new CMSNode(Convert.ToInt32(_data.Value.ToString().Substring(0, 4)));
                                childtxt.Text = firstSaved.Text;
                            }
                            catch
                            {

                            }
                        }

                        base.ContentTemplateContainer.Controls.Add(childtxt);
                        base.ContentTemplateContainer.Controls.Add(extender);
                        break;
                    case "checkbox":

                        checkboxlistNodes = new CheckBoxList();


                        foreach (CMSNode child in parentNode.Children)
                        {
                            addCheckboxNode(child, 1, Convert.ToBoolean(config[2]));

                        }

                        base.ContentTemplateContainer.Controls.Add(checkboxlistNodes);
                        break;
                    case "dropdown":
                        dropdownlistNodes = new DropDownList();

                        dropdownlistNodes.Items.Add(new ListItem("", ""));

                        foreach (CMSNode child in parentNode.Children)
                        {

                            addDropDownListNode(child, 1, Convert.ToBoolean(config[2]));
                        }


                        foreach (string datavalue in datavalues)
                        {
                            dropdownlistNodes.SelectedValue = datavalue;
                        }


                        base.ContentTemplateContainer.Controls.Add(dropdownlistNodes);

                        break;
                    case "listbox":
                        listboxNodes = new ListBox();

                        listboxNodes.SelectionMode = ListSelectionMode.Multiple;
                        listboxNodes.Width = 300;
                        listboxNodes.Height = 200;

                        foreach (CMSNode child in parentNode.Children)
                        {
                            addListboxNode(child, 1, Convert.ToBoolean(config[2]));



                        }

                        base.ContentTemplateContainer.Controls.Add(listboxNodes);
                        break;
                    case "radiobox":

                        radiobuttonlistNodes = new RadioButtonList();


                        foreach (CMSNode child in parentNode.Children)
                        {
                            addRadioButtonNode(child, 1, Convert.ToBoolean(config[2]));

                        }
                        base.ContentTemplateContainer.Controls.Add(radiobuttonlistNodes);
                        break;
                }
            }
            catch { }
        }

        private void addRadioButtonNode(CMSNode node, int level, bool showGrandChildren)
        {
            string preText = string.Empty;

            for (int i = 1; i < level; i++)
            {
                preText += "- ";
            }

            ListItem item = new ListItem(preText + node.Text, node.Id.ToString());

            if (_data.Value.ToString().Contains(node.Id.ToString()))
            {
                item.Selected = true;

            }

            radiobuttonlistNodes.Items.Add(item);

            

            if (showGrandChildren)
            {
                if (node.HasChildren)
                {
                    foreach (CMSNode child in node.Children)
                    {
                        addRadioButtonNode(child, level + 1, showGrandChildren);
                    }
                }
            }
        }

        private void addDropDownListNode(CMSNode node, int level, bool showGrandChildren)
        {
            string preText = string.Empty;

            for (int i = 1; i < level; i++)
            {
                preText += "- ";
            }

            dropdownlistNodes.Items.Add(new ListItem(preText + node.Text, node.Id.ToString()));


            if (showGrandChildren)
            {
                if (node.HasChildren)
                {
                    foreach (CMSNode child in node.Children)
                    {
                        addDropDownListNode(child, level + 1, showGrandChildren);
                    }
                }
            }
        }

        private void addCheckboxNode(CMSNode node, int level, bool showGrandChildren)
        {
            string preText = string.Empty;

            for (int i = 1; i < level; i++)
            {
                preText += "- ";
            }

            ListItem item = new ListItem(preText + node.Text, node.Id.ToString());

            if (_data.Value.ToString().Contains(node.Id.ToString()))
            {
                item.Selected = true;

            }

            checkboxlistNodes.Items.Add(item);
           

            if (showGrandChildren)
            {
                if (node.HasChildren)
                {
                    foreach (CMSNode child in node.Children)
                    {
                        addCheckboxNode(child, level + 1, showGrandChildren);
                    }
                }
            }
        }

        private void addListboxNode(CMSNode node, int level, bool showGrandChildren)
        {
            string preText = string.Empty;

            for (int i = 1; i < level; i++)
            {
                preText += "- ";
            }

            ListItem item = new ListItem(preText + node.Text, node.Id.ToString());

            if (_data.Value.ToString().Contains(node.Id.ToString()))
            {
                item.Selected = true;

            }

            listboxNodes.Items.Add(item);

            if (showGrandChildren)
            {
                if (node.HasChildren)
                {
                    foreach (CMSNode child in node.Children)
                    {
                        addListboxNode(child, level + 1, showGrandChildren);
                    }
                }
            }
        }
    }
}
